package com.cjw.controller.basedata;

import cn.hutool.jwt.JWT;
import com.cjw.config.annotation.OperationLogAnnotation;
import com.cjw.enums.ErrorCode;
import com.cjw.exceptions.BusinessException;
import com.cjw.pojo.dto.database.UserDTO;
import com.cjw.pojo.entity.database.OperationLog;
import com.cjw.pojo.entity.database.User;
import com.cjw.pojo.query.database.LoginDTO;
import com.cjw.pojo.query.database.RegisterUserDTO;
import com.cjw.service.database.UserService;
import com.cjw.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.net.SocketException;
import java.util.Date;

@RestController
@Api("用户管理")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    @ApiOperation("登录")
    public String login(@Valid @RequestBody LoginDTO loginDTO)  {
        return userService.login(loginDTO.getUsername(), loginDTO.getPassword());
    }

    @GetMapping("/getId")
    @ApiOperation("获取id")
    public String getId() {
        UserDTO user = (UserDTO) BaseContextHolder.get("user");
        return user.getId().toString();
    }

    @PostMapping("/logout")
    @ApiOperation("退出")
    public String logout(HttpServletRequest request) {
        String token = request.getHeader("token");
        JWT.of(token).setExpiresAt(new Date());
        return "退出成功";
    }

    @PostMapping("/register")
    @ApiOperation("注册")
    public String register(@Valid @RequestBody RegisterUserDTO registerUserDTO) {
        if (!registerUserDTO.getPassword().equals(registerUserDTO.getConfirmPassword())) {
            throw new BusinessException(ErrorCode.TWO_PASSWORD_NOT_SAME);
        }
        if (registerUserDTO.getPassword().length() < 6 || registerUserDTO.getPassword().length() > 12) {
            throw new BusinessException(ErrorCode.USER_OR_PASSWORD_INVALID);
        }
        new Telephone(registerUserDTO.getPhone());
        return userService.register(registerUserDTO);
    }

    @GetMapping("/getUserHeadUrl")
    @ApiModelProperty("获取头像url")
    public String getUserHeadUrl() {
        return userService.getUserHeadUrl();
    }
}
